from django.shortcuts import render

# Create your views here.
from rest_framework.generics import RetrieveUpdateAPIView
from rest_framework.views import APIView
from django.conf import settings
from urllib.parse import urlencode
from urllib.request import urlopen
from rest_framework.response import Response
import json
import logging
log = logging.getLogger("django")
# Create your views here.
class CaptchaAPIView(APIView):
    def get(self,request):
        """验证码验证接口"""
        AppSecretKey = settings.TENCENT_CAPTCHA.get("App_Secret_Key")
        appid = settings.TENCENT_CAPTCHA.get("APPID")
        Ticket = request.query_params.get("ticket")
        Randstr = request.query_params.get("randstr")
        # 获取客户端的IP地址
        UserIP = request._request.META.get("REMOTE_ADDR")
        params = {
            "aid": appid,
            "AppSecretKey": AppSecretKey,
            "Ticket": Ticket,
            "Randstr": Randstr,
            "UserIP": UserIP
        }
        params = urlencode(params)
        ret = self.txrequest(params)
        return Response({"message":ret})

    def txrequest(self, params):
        url = settings.TENCENT_CAPTCHA.get("GATEWAY")
        content = urlopen("%s?%s" % (url, params)).read()
        res = json.loads(content)
        try:
            return res["response"] == "1"
        except:
            log.error( "验证码错误，%s:%s" % (res["response"], res["err_msg"]) )
            return False


#
# from rest_framework.generics import CreateAPIView
# # from .models import User
# from .serializers import UserModelSerializer
# class UserCreateAPIView(CreateAPIView):
#     queryset = User.objects.all()
#     serializer_class = UserModelSerializer

from rest_framework.mixins import CreateModelMixin
from users.models import User
from .serializers import UserModelSerializer
from rest_framework.viewsets import GenericViewSet
from rest_framework.decorators import action
from rest_framework import status
import re
class UserAPIView(GenericViewSet,CreateModelMixin):
    """用户视图接口"""
    queryset = User.objects.all()
    serializer_class = UserModelSerializer

    @action(methods=["get"],detail=False)
    def mobile(self,request):
        """验证手机号的唯一性"""
        mobile = request.query_params.get("mobile")
        if not re.match("^1[3-9]\d{9}$",mobile):
            return Response({"message":"手机号码格式有误！"}, status=status.HTTP_400_BAD_REQUEST)

        try:
            User.objects.get(mobile=mobile)
            return Response({"message":"手机号已经被注册！"}, status=status.HTTP_400_BAD_REQUEST)
        except:
            return Response({"message":"手机号可以注册使用！"}, status=status.HTTP_200_OK)

from renranapi.libs.yuntongxun.sms import CCP
from django_redis import get_redis_connection
from django.conf import settings
from renranapi.settings import constants
import random
import logging
from mycelery.sms.tasks import send_sms

loger = logging.getLogger("django")
class SMSCodeAPIView(APIView):
    def get(self,request,mobile):
        redis_conn = get_redis_connection("sms_code")
        interval = redis_conn.ttl("interval_%s"%mobile)
        if interval > -1:
            return Response({"message":"对不起,发短信过于频繁,请在%d秒后再次点击发送"%interval},
                            status = status.HTTP_400_BAD_REQUEST)
        # 生成5位验证码,不足6位用0补齐
        sms_code = "%05d" %random.randint(0,99999)
        pipe = redis_conn.pipeline()
        pipe.multi

        pipe.setex('sms_%s'%mobile,constants.SMS_EXPIRE_TIME,sms_code)
        pipe.setex("interval_%s"%mobile,constants.SMS_INTERVAL_TIME,'_')
        pipe.execute()
        send_sms.delay(mobile, sms_code)
        print('验证码是:%s'%sms_code)

        return Response({"message":"短信已发送,请留意手机短信"})



from django.core.mail import send_mail


class EmailAPIView(APIView):
    def get(self,request,mail_addr):
        redis_conn = get_redis_connection("sms_code")
        interval = redis_conn.ttl("interval_%s"%mail_addr)
        if interval > -1:
            return Response({"message":"对不起,发短信过于频繁,请在%d秒后再次点击发送"%interval},
                            status = status.HTTP_400_BAD_REQUEST)
        # 生成6位验证码,不足6位用0补齐
        sms_code = "%05d" %random.randint(0,99999)
        pipe = redis_conn.pipeline()
        pipe.multi

        pipe.setex('sms_%s'%mail_addr,constants.SMS_EXPIRE_TIME,sms_code)
        pipe.setex("interval_%s"%mail_addr,constants.SMS_INTERVAL_TIME,'_')
        pipe.execute()

        print('验证码是:%s'%sms_code)


        msg = '验证码:%s'%sms_code
        try:
            send_mail(
                subject='[91code]您的验证码',
                message=msg,
                from_email=settings.EMAIL_HOST_USER,
                recipient_list=[mail_addr]  # 这里注意替换成自己的目的邮箱，不然就发到我的邮箱来了：）

                )

            return Response({"message":"邮件已发送,请留意邮箱"})
        except:
            return Response({'message':'邮件发送失败,请联系管理员'})

class ForgotPassowrd(APIView):

    def get(self,request):
        print('Entered get method')
        re_pattern_mobile = '^1[3-9]\d{9}$'
        re_pattern_email = '\w+@\w+\.\w+'
        email_mobile = request.query_params.get('email_mobile')
        is_email = re.match(re_pattern_email,email_mobile)
        is_mobile = re.match(re_pattern_mobile,email_mobile)


        # if not is_email and not is_mobile:
        #     return Response({"message":"手机/邮箱格式有误！"}, status=status.HTTP_400_BAD_REQUEST)
        # eli
        if is_mobile:
            try:
                User.objects.get(mobile=email_mobile)
                return Response(status=status.HTTP_200_OK)


            except:
                return Response({"message":"手机尚未注册"}, status=status.HTTP_400_BAD_REQUEST)
        elif is_email:

            try:
                User.objects.get(email=email_mobile)
                return Response(status=status.HTTP_200_OK)

            except:
                return Response({"message": "该邮箱尚未注册！"}, status=status.HTTP_400_BAD_REQUEST)
        else:
            return Response({'message':'请正确填写邮箱或手机号'},status=status.HTTP_400_BAD_REQUEST)


    def put(self,request):
        print('enter put method')
        re_pattern_mobile = '^1[3-9]\d{9}$'
        re_pattern_email = '\w+@\w+\.\w+'
        email_mobile = request.data.get('email_mobile')
        is_email = re.match(re_pattern_email, email_mobile)
        is_mobile = re.match(re_pattern_mobile, email_mobile)

        password = request.data.get('password')
        sms_code = request.data.get('sms_code')
        redis_conn = get_redis_connection('sms_code')
        sms_code_bytes = redis_conn.get("sms_%s" % email_mobile)
        if sms_code != sms_code_bytes.decode():
            return Response({'message':'对不起,验证码无效或已过期'},status=status.HTTP_400_BAD_REQUEST)

        # password2 = request.query_params.get('password2')
        # if password != password2:
        #     return Response({'message':'两次输入密码不一致'},status = status.HTTP_400_BAD_REQUEST)
        if is_email:
            try:
                user = User.objects.get(email=email_mobile)
            except:
                return Response({"message":"该邮箱尚未注册！"},status=status.HTTP_400_BAD_REQUEST)
        elif is_mobile:
            try:
                user = User.objects.get(mobile=email_mobile)
            except:
                return Response({"message": "该手机尚未注册！"}, status=status.HTTP_400_BAD_REQUEST)
        else:
            return Response({'message':'手机或邮箱格式错误'},status.HTTP_400_BAD_REQUEST)
        print('666666')
        user.set_password(password)
        user.save()

        return Response({'message':'密码修改成功!'},status.HTTP_200_OK)

